package com.andengine.editor.textureregioneditor;

import com.andengine.editor.data.TextureFile;
import com.gooddies.graphics.ExtRectangle;
import com.swingson.exceptions.ErrorMessageException;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;

/**
 * @author sad
 */
public class TextureFileWithThumbnail {

    private final TextureFile textureFile;
    private BufferedImage thumbnail;
    private final int size = 40;
    private static BufferedImage transparentImageStub;

    static {
        loadTransparentImageStub();
    }

    private static void loadTransparentImageStub() {
        try {
            try (InputStream stream = TextureFileWithThumbnail.class.getResourceAsStream("/com/andengine/editor/image/transparentImageStub.png")) {
                if (stream == null) {
                    throw new ErrorMessageException("File transparentImageStub.png is not found in spriteeditor package");
                }
                transparentImageStub = ImageIO.read(stream);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public TextureFileWithThumbnail(TextureFile tf) {
        this.textureFile = tf;
        try {
            BufferedImage image = ImageIO.read(new File(tf.getAbsolutePath()));
            ExtRectangle rect = new ExtRectangle(0, 0, image.getWidth(), image.getHeight());
            rect.fitProportional(new Rectangle(size, size));
            thumbnail = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
            Graphics g = thumbnail.getGraphics();
            g.drawImage(transparentImageStub, 0, 0, null);
            g.drawImage(image, size / 2 - (int) rect.getWidth() / 2, size / 2 - (int) rect.getHeight() / 2, (int) rect.getWidth(), (int) rect.getHeight(), null);
            g.setColor(Color.DARK_GRAY);
            g.drawRect(0, 0, size - 1, size - 1);
            g.dispose();
        } catch (IOException ex) {
            throw new ErrorMessageException("Cannot load texture " + tf.getAbsolutePath());
        }
    }

    public TextureFile getTextureFile() {
        return textureFile;
    }

    public BufferedImage getThumbnail() {
        return thumbnail;
    }

    @Override
    public String toString() {
        return getTextureFile().toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof TextureFileWithThumbnail)) {
            return false;
        }

        return getTextureFile().getAbsoluteFile().equals(((TextureFileWithThumbnail) obj).getTextureFile().getAbsoluteFile());
    }

    @Override
    public int hashCode() {
        return getTextureFile().getAbsolutePath().hashCode();
    }
}
